
#!/bin/bash

# ==================== 数据库启动脚本 - 增强版 ====================
# 支持宝塔面板部署，包含强密码配置和连接可靠性保证

echo "🚀 数据库启动脚本启动..."

# 加载环境变量（兼容性处理）
if [ -f ".env" ]; then
    # 兼容性处理：source 和 . 命令
    if command -v source >/dev/null 2>&1; then
        source .env
    else
        . .env
    fi
    echo "✅ 环境变量已加载"
else
    echo "❌ 找不到.env文件，使用默认配置"
fi

# 检查是否在宝塔面板环境
if [ -d "/www/server" ] && [ -d "/www/server/panel" ]; then
    echo "🔧 检测到宝塔面板环境"
    BT_PANEL=true
else
    echo "💻 检测到普通Linux环境"
    BT_PANEL=false
fi

# ==================== PostgreSQL启动 ====================
echo "🗄️ 启动PostgreSQL数据库..."

if [ "$BT_PANEL" = true ]; then
    # 宝塔面板环境
    if systemctl is-active --quiet postgresql; then
        echo "✅ PostgreSQL服务已在运行"
    else
        echo "🚀 启动PostgreSQL服务..."
        sudo systemctl start postgresql
        sudo systemctl enable postgresql
        
        # 等待服务启动
        sleep 3
        
        if systemctl is-active --quiet postgresql; then
            echo "✅ PostgreSQL服务启动成功"
        else
            echo "❌ PostgreSQL服务启动失败，尝试备用方案"
        fi
    fi
else
    # 普通Linux环境
    if pgrep -x "postgres" > /dev/null; then
        echo "✅ PostgreSQL进程已在运行"
    else
        echo "💡 普通环境：请确保PostgreSQL已安装并启动"
        echo "💡 安装命令: sudo apt-get install postgresql postgresql-contrib"
        echo "💡 启动命令: sudo systemctl start postgresql"
    fi
fi

# 创建数据库用户和数据库（如果不存在）
echo "👤 配置PostgreSQL用户和数据库..."
if command -v psql &> /dev/null; then
    # 创建数据库用户
    sudo -u postgres psql -c "CREATE USER $DB_USER WITH PASSWORD '$DB_PASSWORD';" 2>/dev/null || echo "ℹ️ 用户已存在或创建失败"
    
    # 创建数据库
    sudo -u postgres psql -c "CREATE DATABASE $DB_NAME;" 2>/dev/null || echo "ℹ️ 数据库已存在或创建失败"
    
    # 授权用户访问数据库
    sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;" 2>/dev/null || echo "ℹ️ 授权失败"
    
    echo "✅ PostgreSQL用户和数据库配置完成"
else
    echo "⚠️ psql命令不可用，跳过用户配置"
fi

# ==================== Redis启动 ====================
echo "🔴 启动Redis数据库..."

if [ "$BT_PANEL" = true ]; then
    # 宝塔面板环境
    if systemctl is-active --quiet redis; then
        echo "✅ Redis服务已在运行"
    else
        echo "🚀 启动Redis服务..."
        sudo systemctl start redis
        sudo systemctl enable redis
        
        # 等待服务启动
        sleep 2
        
        if systemctl is-active --quiet redis; then
            echo "✅ Redis服务启动成功"
        else
            echo "❌ Redis服务启动失败，使用内存缓存"
        fi
    fi
else
    # 普通Linux环境
    if pgrep -x "redis-server" > /dev/null; then
        echo "✅ Redis进程已在运行"
    else
        echo "💡 普通环境：请确保Redis已安装并启动"
        echo "💡 安装命令: sudo apt-get install redis-server"
        echo "💡 启动命令: sudo systemctl start redis-server"
    fi
fi

# ==================== MongoDB启动 ====================
echo "🍃 启动MongoDB数据库..."

if [ "$BT_PANEL" = true ]; then
    # 宝塔面板环境
    if systemctl is-active --quiet mongod; then
        echo "✅ MongoDB服务已在运行"
    else
        echo "🚀 启动MongoDB服务..."
        sudo systemctl start mongod
        sudo systemctl enable mongod
        
        # 等待服务启动
        sleep 3
        
        if systemctl is-active --quiet mongod; then
            echo "✅ MongoDB服务启动成功"
        else
            echo "❌ MongoDB服务启动失败，使用备用存储"
        fi
    fi
else
    # 普通Linux环境
    if pgrep -x "mongod" > /dev/null; then
        echo "✅ MongoDB进程已在运行"
    else
        echo "💡 普通环境：请确保MongoDB已安装并启动"
        echo "💡 安装命令: 参考MongoDB官方文档"
    fi
fi

# ==================== SQLite备用数据库 ====================
echo "💾 准备SQLite备用数据库..."

# 创建数据目录
mkdir -p data

# 检查SQLite数据库文件
if [ -f "data/bike_wholesale.db" ]; then
    echo "✅ SQLite备用数据库已存在"
else
    echo "📝 创建SQLite备用数据库..."
    # 使用Node.js脚本创建数据库结构
    node scripts/init-sqlite.js
    
    if [ -f "data/bike_wholesale.db" ]; then
        echo "✅ SQLite备用数据库创建成功"
    else
        echo "❌ SQLite备用数据库创建失败"
    fi
fi

# ==================== 数据库连接测试 ====================
echo "🔗 测试数据库连接..."

# 测试PostgreSQL连接
if command -v psql &> /dev/null; then
    echo "🔍 测试PostgreSQL连接..."
    if PGPASSWORD="$DB_PASSWORD" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -c "SELECT version();" &> /dev/null; then
        echo "✅ PostgreSQL连接测试通过 - 使用配置的用户密码"
    else
        echo "❌ PostgreSQL连接测试失败，尝试默认配置"
        if psql -l &> /dev/null; then
            echo "✅ PostgreSQL连接测试通过 - 使用默认配置"
        else
            echo "❌ PostgreSQL连接测试失败"
        fi
    fi
else
    echo "💡 psql命令不可用，跳过PostgreSQL连接测试"
fi

# 测试Redis连接
if command -v redis-cli &> /dev/null; then
    echo "🔍 测试Redis连接..."
    if [ -n "$REDIS_PASSWORD" ]; then
        if redis-cli -h "$REDIS_HOST" -p "$REDIS_PORT" -a "$REDIS_PASSWORD" ping &> /dev/null; then
            echo "✅ Redis连接测试通过 - 使用配置的密码"
        else
            echo "❌ Redis连接测试失败，尝试无密码连接"
            if redis-cli -h "$REDIS_HOST" -p "$REDIS_PORT" ping &> /dev/null; then
                echo "✅ Redis连接测试通过 - 无密码连接"
            else
                echo "❌ Redis连接测试失败"
            fi
        fi
    else
        if redis-cli -h "$REDIS_HOST" -p "$REDIS_PORT" ping &> /dev/null; then
            echo "✅ Redis连接测试通过 - 无密码连接"
        else
            echo "❌ Redis连接测试失败"
        fi
    fi
else
    echo "💡 redis-cli命令不可用，跳过Redis连接测试"
fi

# 测试MongoDB连接
if command -v mongo &> /dev/null; then
    echo "🔍 测试MongoDB连接..."
    if mongo --eval "db.version()" &> /dev/null; then
        echo "✅ MongoDB连接测试通过"
    else
        echo "❌ MongoDB连接测试失败"
    fi
else
    echo "💡 mongo命令不可用，跳过MongoDB连接测试"
fi

# ==================== 宝塔面板优化 ====================
if [ "$BT_PANEL" = true ]; then
    echo "🔧 宝塔面板优化配置..."
    
    # 创建宝塔面板数据库管理脚本
    cat > /tmp/bt-database-manager.sh << 'EOF'
#!/bin/bash
# 宝塔面板数据库管理脚本

case "$1" in
    start)
        systemctl start postgresql
        systemctl start redis
        systemctl start mongod
        echo "数据库服务已启动"
        ;;
    stop)
        systemctl stop postgresql
        systemctl stop redis
        systemctl stop mongod
        echo "数据库服务已停止"
        ;;
    restart)
        systemctl restart postgresql
        systemctl restart redis
        systemctl restart mongod
        echo "数据库服务已重启"
        ;;
    status)
        echo "PostgreSQL: $(systemctl is-active postgresql)"
        echo "Redis: $(systemctl is-active redis)"
        echo "MongoDB: $(systemctl is-active mongod)"
        ;;
    *)
        echo "用法: $0 {start|stop|restart|status}"
        ;;
esac
EOF
    
    chmod +x /tmp/bt-database-manager.sh
    echo "✅ 宝塔面板数据库管理脚本已创建: /tmp/bt-database-manager.sh"
    
    # 创建宝塔面板数据库配置文件
    cat > /tmp/bt-database-config.json << EOF
{
    "databases": [
        {
            "name": "PostgreSQL",
            "type": "postgresql",
            "port": 5432,
            "status": "$(systemctl is-active postgresql)"
        },
        {
            "name": "Redis",
            "type": "redis", 
            "port": 6379,
            "status": "$(systemctl is-active redis)"
        },
        {
            "name": "MongoDB",
            "type": "mongodb",
            "port": 27017,
            "status": "$(systemctl is-active mongod)"
        }
    ],
    "backup_database": {
        "name": "SQLite",
        "type": "sqlite",
        "file": "data/bike_wholesale.db",
        "status": "$(if [ -f data/bike_wholesale.db ]; then echo active; else echo inactive; fi)"
    }
}
EOF
    
    echo "✅ 宝塔面板数据库配置文件已创建: /tmp/bt-database-config.json"
fi

# ==================== 数据库状态报告 ====================
echo ""
echo "📊 数据库状态报告:"
echo "=================="

# PostgreSQL状态
if [ "$BT_PANEL" = true ]; then
    PG_STATUS=$(systemctl is-active postgresql)
else
    if pgrep -x "postgres" > /dev/null; then
        PG_STATUS="active"
    else
        PG_STATUS="inactive"
    fi
fi
echo "PostgreSQL: $PG_STATUS"

# Redis状态
if [ "$BT_PANEL" = true ]; then
    REDIS_STATUS=$(systemctl is-active redis)
else
    if pgrep -x "redis-server" > /dev/null; then
        REDIS_STATUS="active"
    else
        REDIS_STATUS="inactive"
    fi
fi
echo "Redis: $REDIS_STATUS"

# MongoDB状态
if [ "$BT_PANEL" = true ]; then
    MONGO_STATUS=$(systemctl is-active mongod)
else
    if pgrep -x "mongod" > /dev/null; then
        MONGO_STATUS="active"
    else
        MONGO_STATUS="inactive"
    fi
fi
echo "MongoDB: $MONGO_STATUS"

# SQLite状态
if [ -f "data/bike_wholesale.db" ]; then
    SQLITE_STATUS="active"
else
    SQLITE_STATUS="inactive"
fi
echo "SQLite备用: $SQLITE_STATUS"

echo "=================="
echo ""

# 最终状态检查
if [ "$PG_STATUS" = "active" ] || [ "$REDIS_STATUS" = "active" ] || [ "$SQLITE_STATUS" = "active" ]; then
    echo "🎉 数据库服务启动完成！"
    echo "💡 至少有一个数据库服务可用"
else
    echo "⚠️ 警告：所有数据库服务都不可用"
    echo "💡 应用将使用内存存储（功能受限）"
fi

echo ""
echo "💡 数据库管理命令:"
if [ "$BT_PANEL" = true ]; then
    echo "   启动所有数据库: sudo systemctl start postgresql redis mongod"
    echo "   停止所有数据库: sudo systemctl stop postgresql redis mongod"
    echo "   查看数据库状态: sudo systemctl status postgresql redis mongod"
else
    echo "   请根据您的环境使用相应的数据库管理命令"
fi

echo ""
echo "🚀 数据库启动脚本执行完成！"